<?php
namespace App\Domain;

use App\Model\Sync as ModelSync;
use App\Model\Order as ModelOrder;
use App\Model\Member as ModelMember;
use App\Model\Area as ModelArea;
use App\Model\Goods as ModelGoods;

class Sync {

    const PIN_TUAN_SUCCESS = 'QuJusTIrlvNSDACXFR-JLKxx5muENWOQoCLoFoo5IIM';
    const PIN_TUAN_RETURN = 'lqo4SiTwqhbUFNW-Duak7GTeryQYOPSSPP4w9xBUTzg';
    const ORDER_SHIPPING = 'sGFyFDpdTXqX0yvfwSzV5Pxq9VM5_1cvRBC3QeetwmM';
    //发货是否已签收，签收自动确认收货，不需要用户手动
    public function shipping() {
        $sync_model = new ModelSync();
        $order_model = new ModelOrder();
        //查询所有已发货状态的订单
        $order_info = $order_model->getAllOrder();
        foreach ( $order_info as $k => $v ){
            $goods_info = $order_model->getOrderGoodsDetail( $v['order_id'] );
            $delivery_info = $order_model->getOrderGoodsDelivery( $goods_info[0]['delivery_id'] );
            //发起get请求
            $url = "https://m.kuaidi100.com/query?type=".$delivery_info['shipping_code']."&postid=".$delivery_info['invoice_no']."&id=1&valicode=&temp=0.49738534969422676";
            $res = $this->httpRequest( $url, 'get' );
            if( $res['state'] !=3 ){
                continue;
            }
            //更改订单状态为已签收(待评价)
            $order_model->changeOrderStatus( $v['order_id'] );
            //增加商品销量
            $order_model->changeGoodsSaleNum( $v['goods_id'], $v['goods_num'] );
        }
        return 1;
    }

    //拼团(自动退款由后台计划任务处理，防止同时处理表造成数据错误，更改订单状态)，加库存
    public function pinTuan() {
        $sync_model = new ModelSync();
        $order_model = new ModelOrder();
        $goods_model = new ModelGoods();
        $time = time();
        //查询所有暂未拼成功的订单(found,follow)
        $found_info = $order_model->getAllFound();
        foreach ( $found_info as $k => $v ){
            //如果已经超过拼团时间，至为失败(包括follow表)+库存还原
            if( $v['found_end_time'] < $time && $v['need'] > $v['join'] ){
                $order_model->changeFoundFail( $v['found_id'] );
                //处理团长的商品信息
                $found_goods_info = $order_model->getTemporaryById( $v['order_id'] );
                $found_child_goods_info = json_decode( $found_goods_info[0]['goods_info'], true ); //todo 会不会报错？
                foreach ( $found_child_goods_info as $k_found => $v_found ){
                    //根据goods_id，spec_key 来加库存(规格表)
                    $order_model->changeSpecNum( $v_found['goods_id'],$v_found['spec_key'], $v_found['goods_num'], 2 );
                    //根据goods_id，来加库存(商品表)
                    $order_model->changeGoodsNum( $v_found['goods_id'], $v_found['goods_num'], 2 );
                }

                //根据found_Id查询所有的follow订单   foreach中写，不会太过影像效率，因为follow不会有太多条
                $follow_info = $order_model->getConFollow( $v['found_id'] );
                //处理团员的状态及库存
                foreach( $follow_info as $kk => $vv ){
                    $order_model->changeFollowFail( $vv['follow_id'] );
                    //根据order_id关联临时表获取商品信息进行库存的还原
                    $follow_goods_info = $order_model->getTemporaryById( $vv['order_id'] );
                    $child_goods_info = json_decode( $follow_goods_info[0]['goods_info'], true ); //todo 会不会报错？
                    foreach ( $child_goods_info as $kkk => $vvv ){
                        //根据goods_id，spec_key 来加库存(规格表)
                        $order_model->changeSpecNum( $vvv['goods_id'],$vvv['spec_key'], $vvv['goods_num'], 2 );
                        //根据goods_id，来加库存(商品表)
                        $order_model->changeGoodsNum( $vvv['goods_id'], $vvv['goods_num'], 2 );
                    }
                }

            }
        }
        return 1;
    }

    //消息推送
    public function sendMes() {
        $sync_model = new ModelSync();
        $order_model = new ModelOrder();
        $goods_model = new ModelGoods();
        //1.拼团成功
        $order_info = $order_model->getAllFoundOrder();
        foreach ( $order_info as $k => $v ){
            $send_message = array();
            $send_message['keyword1'] = array("value" => $v['goods_name'], "color" => "#173177"); //商品名称
            $send_message['keyword2'] = array("value" => $v['order_sn'], "color" => "#173177"); //订单号
            $send_message['keyword3'] = array("value" => $v['goods_price'], "color" => "#173177");//原价
            $send_message['keyword4'] = array("value" => $v['final_price'], "color" => "#173177");//拼团价
            $send_message['keyword5'] = array("value" => '如果未按承诺时间发货，系统将按照规则进行赔偿。', "color" => "#173177");//温馨提示
            $res = \PhalApi\DI()->wechatmini->sendWeAppMessage( $v['openid'], $v['form_id'], self::PIN_TUAN_SUCCESS, '', '', $send_message );
            //修改订单is_send状态
            $order_model->changeOrderSend($v['order_sn']);
        }

        //2.退款
        $return_info = $order_model->getAllReturnOrder();
        foreach ( $return_info as $k => $v ){
            $send_message = array();
            $send_message['keyword1'] = array("value" => $v['goods_name'], "color" => "#173177"); //商品名称
            $send_message['keyword2'] = array("value" => $v['order_sn'], "color" => "#173177"); //订单号
            $send_message['keyword3'] = array("value" => $v['refund_amount'], "color" => "#173177");//退款金额
            $send_message['keyword4'] = array("value" => $v['admin_message'], "color" => "#173177");//退款原因
            $res = \PhalApi\DI()->wechatmini->sendWeAppMessage( $v['openid'], $v['form_id'], self::PIN_TUAN_RETURN, '', '', $send_message );
            //修改订单is_send状态
            $order_model->changeReturnOrderSend($v['order_sn']);
        }

        //3.订单发货
        $shipping_info = $order_model->getAllShippingOrder();
        foreach ( $shipping_info as $k => $v ){
            $goods_info = $order_model->getOrderGoodsDetail( $v['order_id'] );
            $delivery_info = $order_model->getOrderGoodsDelivery( $goods_info[0]['delivery_id'] );
            //地址信息
            $model_area = new ModelArea();
            $province = $model_area->getAreaInfo( $v['province'] );
            $city = $model_area->getAreaInfo( $v['city'] );
            $district = $model_area->getAreaInfo( $v['district'] );
            $address = $province['name'].$city['name'].$district['name'].$v['address'];
            $send_message = array();
            $send_message['keyword1'] = array("value" => $v['goods_name'], "color" => "#173177"); //商品名称
            $send_message['keyword2'] = array("value" => $v['order_sn'], "color" => "#173177"); //订单号
            $send_message['keyword3'] = array("value" => $v['order_amount'], "color" => "#173177");//订单金额
            $send_message['keyword4'] = array("value" => $delivery_info['shipping_name'], "color" => "#173177");//物流公司
            $send_message['keyword5'] = array("value" => $delivery_info['invoice_no'], "color" => "#173177");//物流单号
            $send_message['keyword6'] = array("value" => $address, "color" => "#173177");//收货地址
            $res = \PhalApi\DI()->wechatmini->sendWeAppMessage( $v['openid'], $v['form_id'], self::ORDER_SHIPPING, '', '', $send_message );
            //修改订单is_send状态
            $order_model->changeOrderSend($v['order_sn']);
        }
        return 1;
    }

    //处理购物车的商品+拼团商品到期处理
    public function cartGoods(){
        $model = new ModelGoods();
        //查询所有拼团商品
        $pintuan_info = $model->getGoodsProm( 6 );
        foreach ( $pintuan_info as $k => $v ){
            $team_info = $model->getTeam( $v['goods_id'] );
            if( $team_info['activity_end_time'] <time()){
                $model->updateOnSale( $v['goods_id'] );
                $model->updateTeamStatus( $team_info['team_id'] );
            }
        }
        //查询所有促销商品
        $goods_info = $model->getGoodsProm( 3 );
        foreach ( $goods_info as $k => $v ){
            if( $v['prom_start_time']>time() || $v['prom_end_time']<time() || ( $v['store_count'] == 0 )){
                //促销过期，将商品类型至为0，并删除存在购物车里的商品
                $model->updateGoods( $v['goods_id'] );
                //根据goods_Id删除购物车商品，不需要按规格
                $model->deleteCartByGoods( $v['goods_id'] );
            }
        }
    }
}
